<script lang="ts">
  export default {
    name: 'GoodsDetail',
  };
</script>

<script setup lang="ts">
  import { computed, onMounted, ref, watch } from 'vue';
  import { useWindowSize } from '@vueuse/core';
  import { showToast, showImagePreview } from 'vant';
  import { useRouter, useRoute } from 'vue-router';
  import { useShopNav } from '@/store/modules/app';

  import API_HOME from '@/apis/home';
  import { useI18n } from 'vue-i18n';
  const { t } = useI18n();
  const router = useRouter();
  const route = useRoute()
  const { width } = useWindowSize();
  const appStore = useShopNav();
  // 商品数据
  const list = ref([
  ])
  const product = ref({
    images: [],
    price: '',
    original_price: ''
  });
  // 商品SKU收集
  let goods_sku_price_id = ref('')
  let showWatchAll = ref(false)
  const selectedSize = ref({
  });
  const selectedColor = ref('#000000');
  const quantity = ref(1);
  const activePreviewIndex = ref(0);
  let goodsID = ref('')


  // 获取商品详情
  const getDetail = async () => {
    // 清空规格选项
    selectedSize.value = {}
    let res = await API_HOME.goodsDetail({
      id: goodsID.value
    })
    if (res.code == 1) {
      product.value = res.data
      // 模拟数据
      product.value['features'] = [
        '80% Organic Cotton, 20% Recycled Polyester',
        'Premium fleece lining for warmth',
        'Kangaroo pocket for convenience',
        'Adjustable drawstring hood',
        'Ribbed cuffs and hem for better fit'
      ]
      // 获取猜你喜欢数据
      getLikeGoods()
    }

  }

  // 响应式判断
  const isMobile = computed(() => width.value < 768);

  // 图片预览 - 添加了onChange回调
  const showImageGallery = () => {
    showImagePreview({
      images: product.value.images,
      startPosition: activePreviewIndex.value,
      closeable: true,
      closeOnPopstate: true,
      maxZoom: 3,
      closeIconPosition: 'top-right',
      onChange: (index) => {
        // 预览切换时更新当前索引
        activePreviewIndex.value = index;
      }
    });
  };

  // 切换主图
  const changePreviewImage = (index: number) => {
    activePreviewIndex.value = index;
  };

  // 上一张图片
  const prevImage = () => {
    if (activePreviewIndex.value > 0) {
      activePreviewIndex.value--;
    }
  };

  // 下一张图片
  const nextImage = () => {
    if (activePreviewIndex.value < product.value.images.length - 1) {
      activePreviewIndex.value++;
    }
  };

  // 添加到购物车
  const addToCart = async (type) => {
    if (product.value.skus.length == 0) {
      goods_sku_price_id.value = product.value.sku_prices[0].id
    }
    if (!goods_sku_price_id.value) {
      return showToast({
        message: t('home.PleaseSelectTheSpecification'),
        icon: 'warning',

      });
    } else {
      let res = await API_HOME.cartUpdate({
        goods_id: goodsID.value,
        goods_num: quantity.value,
        goods_sku_price_id: goods_sku_price_id.value,
        type
      })
      await appStore.getCarList()
      setTimeout(() => {
        showToast({
          message: t('cart.addSuccess'),
          icon: 'success',
          position: 'top'
        });
      }, 500);

    }
  };

  // 立即购买
  const buyNow = () => {
    if (product.value.skus.length == 0) {
      goods_sku_price_id.value = product.value.sku_prices[0].id
    }
    if (!goods_sku_price_id.value) {
      return showToast({
        message: t('home.PleaseSelectTheSpecification'),
        icon: 'warning',

      });
    }
    appStore.setCheckedFrom('goods')
    let arr = [{
      goods_id: goodsID.value,
      goods_num: quantity.value,
      goods_sku_price_id: goods_sku_price_id.value,

    }]
    appStore.setCartCheckList(arr)
    showToast({
      message: 'loading...',
      icon: 'cart-o',
      position: 'top'
    });
    setTimeout(() => {
      router.push('/cart');
    }, 1500);
  };

  // 增加/减少数量
  const increaseQuantity = () => {
    quantity.value++;
  };

  const decreaseQuantity = () => {
    if (quantity.value > 1) {
      quantity.value--;
    }
  };

  function findSkuBySkuIds (skuList, targetSkuIds) {
    // 1. 将目标 skuIds 按逗号分割、排序、重新拼接（确保顺序一致）
    const normalizedTarget = targetSkuIds
      .split(',')
      .sort()
      .join(',');

    // 2. 遍历数组，找到匹配的项
    return skuList.find((item) => {
      const normalizedItem = item.goods_sku_ids
        .split(',')
        .sort()
        .join(',');
      return normalizedItem === normalizedTarget;
    });
  }
  // 查找skuPrice
  let filterSkusPrice = (data) => {
    // 根据选择的规格查找价格
    const matchedItem = findSkuBySkuIds(product.value.sku_prices, data);
    console.log(matchedItem, data, '查找SKU结果');
    return matchedItem
  }
  // 选择规格
  const handleSelected = (data, index) => {
    // 根据id显示选择颜色
    selectedSize.value[`size${index}`] = data.id
    console.log(selectedSize.value, '规格ID');
    // 将对象的值合并成逗号分隔的字符串
    const sizeValues = Object.values(selectedSize.value);
    const sizeString = sizeValues.join(',');
    let skuData = filterSkusPrice(sizeString)
    if (skuData) {
      product.value.original_price = skuData.original_price
      product.value.price = skuData.price
      goods_sku_price_id.value = skuData.id
    }

  }

  // 获取猜你喜欢列表
  let getLikeGoods = async () => {
    let gId = product.value.category_ids.split(',')
    let res = await API_HOME.goodsLike({
      category_id: gId[0],
      goods_id: goodsID.value
    })
    if (res.code == 1) {
      list.value = res.data
    }
  }
  let CommentList = ref({})
  // 获取评论数据
  let getComment = async () => {
    let res = await API_HOME.goodsComment({
      goods_id: goodsID.value
    })
    if (res.code == 1) {
      res.data.sumLevel = Number(res.data.sumLevel)
      CommentList.value = res.data
    }
  }
  let closeC = () => {
    showWatchAll.value = false

  }
  watch(() => route.query.goodsId, (newVal, oldVal) => {
    if (newVal && newVal != oldVal) {
      console.log(1);
      goodsID.value = newVal
      getDetail()
      getComment()
      appStore.getCarList()
    }
  }, { immediate: true })
  // 初始化
  onMounted(() => {

  })
</script>

<template>
  <div>
    <Shop_headers></Shop_headers>
    <div class="shopContainer">
      <div class="description">
        <!-- 商品详情容器 -->
        <div class="product-detail-container">
          <!-- 图片预览区域 -->
          <div class="product-gallery">
            <div class="main-image" @click="showImageGallery">
              <img :src="product.images[activePreviewIndex]" :alt="product.name" />
              <div class="image-overlay">
                <!-- <van-icon name="zoom-in" size="24" color="#fff" />
                <span>Click to Preview</span> -->
                <van-icon name="eye-o" size="36" color="#fff" />
              </div>

              <!-- PC端左右切换按钮 -->
              <div v-if="!isMobile" class="pc-navigation">
                <div class="nav-button prev" @click.stop="prevImage">
                  <van-icon name="arrow-left" size="24" color="#fff" />
                </div>
                <div class="nav-button next" @click.stop="nextImage">
                  <van-icon name="arrow" size="24" color="#fff" />
                </div>
              </div>

              <!-- 图片索引指示器 -->
              <div class="image-indicator">
                {{ activePreviewIndex + 1 }} / {{ product.images.length }}
              </div>
            </div>

            <div class="thumbnail-list">
              <div v-for="(image, index) in product.images" :key="index" class="thumbnail"
                :class="{ 'active': activePreviewIndex === index }" @click="changePreviewImage(index)">
                <img :src="image" :alt="'Thumbnail ' + (index + 1)" />
              </div>
            </div>
          </div>

          <!-- 商品信息区域 -->
          <div class="product-info">
            <h1 class="product-title">{{ product.title }}</h1>
            <div class="product-price">
              <span class="sale-price">${{ product.price }}</span>
              <span class="original-price">{{ product.original_price }}</span>
              <span class="discount" v-if="false">20% OFF</span>
            </div>

            <div class="product-rating">
              <van-rate v-model="CommentList.sumLevel" readonly allow-half color="#ee0a24" void-color="#eee" />
              <span class="rating-value">{{CommentList.sumLevel}}</span>
              <span class="reviews">( <van-icon name="eye" />{{CommentList.views}} )</span>
            </div>

            <p class="product-description">
              {{ product.description }}
            </p>
            <div class="product-meta">

              <div class="meta-item" v-for="(i,index) in product.service" :key="index">
                <van-icon name="passed" color="#07c160" />
                <span>
                  <h3 style="margin: 0">{{i.name}}</h3>
                  <div>{{i.description}}</div>
                </span>
              </div>

            </div>
            <div class="product-features" v-if="false">
              <h3>Features:</h3>
              <ul>
                <li v-for="(feature, index) in product.features" :key="index">{{ feature }}</li>
              </ul>
            </div>

            <!-- <div class="color-selector">
              <h3>Color:</h3>
              <div class="color-options">
                <div v-for="(color, index) in product.colors" :key="index" class="color-option"
                  :class="{ 'selected': selectedColor === color.value }" :style="{ backgroundColor: color.value }"
                  @click="selectedColor = color.value">
                  <van-icon v-if="selectedColor === color.value" name="success" color="#fff" />
                </div>
              </div>
            </div> -->

            <div class="size-selector" v-for="(i,index) in product.skus" :key="i.id">
              <h3>{{i.name}}:</h3>
              <div class="size-options">
                <div v-for="(size, index) in i.children" :key="index" class="size-option"
                  :class="{ 'selected': selectedSize[`size${i.id}`] === size.id }" @click="handleSelected(size,i.id)">
                  {{ size.name }}
                </div>
              </div>
              <!-- <a href="#" class="size-guide">Size Guide</a> -->
            </div>

            <div class="quantity-selector">
              <h3>{{t('home.Quantity')}}:</h3>
              <div class="quantity-control">
                <!-- <van-button round size="small" @click="decreaseQuantity">-</van-button> -->
                <!-- <span class="quantity-value">{{ quantity }}</span> -->
                <!-- <van-button round size="small" @click="increaseQuantity">+</van-button> -->
                <van-stepper v-model="quantity" integer />
              </div>
            </div>

            <div class="action-buttons">
              <van-button round block size="large" type="primary" class="add-to-cart" @click="addToCart('inc')">
                <van-icon name="cart-circle-o" /> {{t('home.AddToCart')}}
              </van-button>

              <van-button round block size="large" class="buy-now" @click="buyNow">
                <van-icon name="cash-back-record" />{{t('home.BuyNow')}}
              </van-button>
            </div>


          </div>
        </div>

        <!-- 商品详情底部区域 -->
        <div class="product-detail-bottom">
          <!-- 商品描述 -->
          <div class="detail-section">
            <h2>{{t('home.prodDetail')}}</h2>
            <div v-html="product.content"></div>
          </div>

          <!-- 商品评价 -->
          <div class="detail-section">
            <h2>{{t('home.CustomerReviews')}}</h2>
            <div class="review-summary">
              <div class="overall-rating">
                <div class="rating-value">{{CommentList.sumLevel}}</div>
                <div class="rating-stars">
                  <van-rate v-model="CommentList.sumLevel" readonly allow-half color="#ee0a24" void-color="#eee"
                    size="20" />
                </div>
                <div class="rating-count">{{CommentList.views}} {{t('home.reviews')}}</div>
              </div>
              <div class="rating-bars">
                <div class="rating-bar" v-for="(i,index) in CommentList.levels" :key="index">
                  <span>{{i.level}} {{t('home.stars')}}</span>
                  <van-progress :percentage="parseInt(i.percent.replace('%', ''))" stroke-width="8" color="#ffd21e" />
                  <span>{{i.percent}}</span>
                </div>
              </div>
            </div>
            <!-- 用户评论列表 -->
            <div class="reviews-list">
              <div v-for="(review, index) in product.reviews" :key="index" class="review-item">
                <div class="review-header">
                  <div class="user-avatar">{{ review.user.charAt(0) }}</div>
                  <div class="user-info">
                    <div class="user-name">{{ review.user }}</div>
                    <div class="review-date">{{ review.date }}</div>
                  </div>
                  <div class="review-rating">
                    <van-rate v-model="review.rating" readonly allow-half color="#ee0a24" void-color="#eee" size="14" />
                  </div>
                </div>
                <div class="review-content">
                  {{ review.comment }}
                </div>
              </div>
            </div>

            <van-button round plain type="primary" block
              @click="showWatchAll=true">{{t('home.ViewAllReviews')}}</van-button>
          </div>
        </div>
      </div>

      <!-- 相关商品 -->
      <div class="related-products">
        <h2 class="section-title">{{t('home.AlsoLike')}}</h2>
        <Goods_list :filteredProducts="list"></Goods_list>
      </div>
    </div>
    <Shop_allEvaluate :show="showWatchAll" :goodId="goodsID" @closeLan="closeC"></Shop_allEvaluate>
    <Shop_footer></Shop_footer>
  </div>
</template>

<style lang="less" scoped>
  @import './index.less';
</style>